<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class ProfileController extends AbstractActionController
{
    /**
    * Entity manager instance
    *
    * @var Doctrine\ORM\EntityManager
    */
    protected $em;

    /**
    * Returns an instance of the Doctrine entity manager loaded from the service
    * locator
    *
    * @return Doctrine\ORM\EntityManager
    */
    
    public function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()
                ->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }
    
    public function indexAction()
    {
        $message = null;
        $id = $this->zfcUserAuthentication()->getIdentity()->getId();
        $utilisateur = $this->getEntityManager()->find('Application\Model\Entity\Utilisateur', $id);
        
        $fsm = $this->getServiceLocator()->get('FormElementManager');
        $form = $fsm->get('Application\Form\ProfileForm');
        $form->bind($utilisateur);
        
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = $request->getPost();
            $form->setData($data);
            
            if ($form->isValid()) {
                $this->getEntityManager()->persist($utilisateur);
                $this->getEntityManager()->flush();
                $message = 'Profil modifié !';
            }
        }

        return array(
            'form' => $form,
            'message' => $message,
        );
    }
}

